import 'package:get/get.dart';
import '../model/post_model.dart';
import '../data/post_data.dart';

/// 植物养殖帖子状态管理
/// 使用GetX进行全局状态管理，采用非常规命名避免标准模式
class PostState extends GetxController {
  // 所有帖子
  final RxList<PostModel> _allPosts = <PostModel>[].obs;

  // 当前选中的帖子
  final Rx<PostModel?> _currentPost = Rx<PostModel?>(null);

  // 当前筛选分类
  final Rx<PostCategory?> _currentCategory = Rx<PostCategory?>(null);

  // 当前搜索关键词
  final RxString _searchKeyword = ''.obs;

  /// 获取所有帖子
  List<PostModel> get allPosts => _allPosts.toList();

  /// 获取当前帖子
  PostModel? get currentPost => _currentPost.value;

  /// 获取当前筛选分类
  PostCategory? get currentCategory => _currentCategory.value;

  /// 获取当前搜索关键词
  String get searchKeyword => _searchKeyword.value;

  /// 获取筛选后的帖子列表
  List<PostModel> get filteredPosts {
    List<PostModel> posts = _allPosts.toList();

    // 按分类筛选
    if (_currentCategory.value != null) {
      posts =
          posts
              .where((post) => post.category == _currentCategory.value)
              .toList();
    }

    // 按关键词搜索
    if (_searchKeyword.value.isNotEmpty) {
      final keyword = _searchKeyword.value.toLowerCase();
      posts =
          posts.where((post) {
            return post.title.toLowerCase().contains(keyword) ||
                post.content.toLowerCase().contains(keyword) ||
                post.tags.any((tag) => tag.toLowerCase().contains(keyword));
          }).toList();
    }

    // 按发布时间降序排序（最新的在前面）
    posts.sort((a, b) => b.publishTime.compareTo(a.publishTime));

    return posts;
  }

  /// 获取指定分类的帖子
  List<PostModel> getPostsByCategory(PostCategory category) {
    return _allPosts.where((post) => post.category == category).toList()
      ..sort((a, b) => b.publishTime.compareTo(a.publishTime));
  }

  /// 获取指定用户的帖子
  List<PostModel> getPostsByUserId(String userId) {
    return _allPosts.where((post) => post.userId == userId).toList()
      ..sort((a, b) => b.publishTime.compareTo(a.publishTime));
  }

  /// 获取图片类型的帖子
  List<PostModel> getImagePosts() {
    return _allPosts
        .where((post) => post.resourceType == ResourceType.image)
        .toList()
      ..sort((a, b) => b.publishTime.compareTo(a.publishTime));
  }

  /// 获取视频类型的帖子
  List<PostModel> getVideoPosts() {
    return _allPosts
        .where((post) => post.resourceType == ResourceType.video)
        .toList()
      ..sort((a, b) => b.publishTime.compareTo(a.publishTime));
  }

  /// 获取热门帖子（按发布时间排序）
  List<PostModel> getPopularPosts() {
    return _allPosts.toList()
      ..sort((a, b) => b.publishTime.compareTo(a.publishTime));
  }

  /// 获取最新帖子
  List<PostModel> getLatestPosts() {
    return _allPosts.toList()
      ..sort((a, b) => b.publishTime.compareTo(a.publishTime));
  }

  /// 添加新帖子
  void addPost(PostModel post) {
    if (post.isValid) {
      _allPosts.add(post);
      // 按发布时间降序排序
      _allPosts.sort((a, b) => b.publishTime.compareTo(a.publishTime));
    }
  }

  /// 更新帖子
  void updatePost(PostModel updatedPost) {
    final index = _allPosts.indexWhere((post) => post.id == updatedPost.id);
    if (index != -1 && updatedPost.isValid) {
      _allPosts[index] = updatedPost;

      // 如果当前帖子被更新，也要更新当前帖子
      if (_currentPost.value?.id == updatedPost.id) {
        _currentPost.value = updatedPost;
      }

      // 重新排序
      _allPosts.sort((a, b) => b.publishTime.compareTo(a.publishTime));
    }
  }

  /// 删除帖子
  void deletePost(String postId) {
    _allPosts.removeWhere((post) => post.id == postId);

    // 如果删除的是当前帖子，清空当前帖子
    if (_currentPost.value?.id == postId) {
      _currentPost.value = null;
    }
  }

  /// 设置当前帖子
  void setCurrentPost(PostModel? post) {
    _currentPost.value = post;
  }

  /// 设置筛选分类
  void setCategoryFilter(PostCategory? category) {
    _currentCategory.value = category;
  }

  /// 设置搜索关键词
  void setSearchKeyword(String keyword) {
    _searchKeyword.value = keyword;
  }

  /// 清空筛选条件
  void clearFilters() {
    _currentCategory.value = null;
    _searchKeyword.value = '';
  }

  /// 根据ID获取帖子
  PostModel? getPostById(String postId) {
    try {
      return _allPosts.firstWhere((post) => post.id == postId);
    } catch (e) {
      return null;
    }
  }

  /// 创建新的帖子实例
  PostModel createNewPost({
    required String userId,
    required PostCategory category,
    required String title,
    required String content,
    List<String> tags = const [],
    required ResourceType resourceType,
    required String resourcePath,
    String? coverImagePath,
  }) {
    return PostModel(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      userId: userId,
      category: category,
      title: title,
      content: content,
      tags: tags.take(5).toList(), // 限制最多5个标签
      resourceType: resourceType,
      resourcePath: resourcePath,
      coverImagePath: coverImagePath,
      publishTime: DateTime.now(),
    );
  }

  /// 获取所有标签（去重）
  List<String> getAllTags() {
    final allTags = <String>{};
    for (final post in _allPosts) {
      allTags.addAll(post.tags);
    }
    return allTags.toList()..sort();
  }

  /// 根据标签获取帖子
  List<PostModel> getPostsByTag(String tag) {
    return _allPosts.where((post) => post.tags.contains(tag)).toList()
      ..sort((a, b) => b.publishTime.compareTo(a.publishTime));
  }

  /// 帖子总数
  int get postCount => _allPosts.length;

  /// 各分类帖子数量
  Map<PostCategory, int> get categoryCounts {
    final counts = <PostCategory, int>{};
    for (final category in PostCategory.values) {
      counts[category] =
          _allPosts.where((post) => post.category == category).length;
    }
    return counts;
  }

  @override
  void onInit() {
    super.onInit();
    _loadDefaultData();
  }

  /// 加载默认数据
  void _loadDefaultData() {
    _allPosts.assignAll(PostData.getDefaultPosts());
  }
}
